<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <!-- import CSS -->
    <link rel="stylesheet" href="/css/element.css">
    <link rel="stylesheet" href="/css/index.css">
    <title>迅雷NAS批量下载</title>
</head>
<body>
<div id="app">
    <h3>文档地址：
        <a href="https://blog.csdn.net/qq_41417649/article/details/139294157" target="_blank">
        https://blog.csdn.net/qq_41417649/article/details/139294157</a></h3>
    <el-input
            type="textarea"
            :rows="10"
            placeholder="请输入内容"
            v-model="baseInfoStr">
    </el-input>
    <el-button @click="parseBaseInfo">解析</el-button>
<!--    <el-button @click="watch">watch</el-button>
    <el-button @click="downloadPath">downloadPath</el-button>
    <el-button @click="files('')">files</el-button>-->

    <el-tabs v-model="activeName">
        <el-tab-pane label="文件列表" name="files">
            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <div class="downHeader">
                        <div class="filePath">
                            <div class="path" @click="filesRoute('',0)">全部文件</div>
                            <template v-for="(item,index) in filePaths">
                                <span>/</span>
                                <div class="path" @click="filesRoute(item.id,index+1)">{{item.name}}</div>
                            </template>
                        </div>
                        <el-button class="download" v-if="nextPageToken" type="text" @click="files()">下一页
                        </el-button>
                        <el-button class="download" type="text" @click="showDownload = true"
                                   :disabled="!fileListSelection.length">批量下载
                        </el-button>
                    </div>
                </div>
                <el-table :data="fileList" v-loading="fileListLoading"
                          @row-click="fileListClick"
                          @selection-change="handleFileListSelectionChange"
                          show-overflow-tooltip>
                    <el-table-column type="selection" width="55" :selectable="fileListSelectDisabled"></el-table-column>
                    <el-table-column prop="icon_link" label="" width="52">
                        <template slot-scope="scope">
                            <el-image style="width: 32px; height: 32px" :src="scope.row.icon_link"></el-image>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="名称"></el-table-column>
                    <el-table-column prop="file_extension" label="后缀" align="center" width="60"></el-table-column>
                    <el-table-column prop="size" label="大小" align="center" width="80">
                        <template slot-scope="scope">
                            {{sizeParse(scope.row.size)}}
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </el-tab-pane>
        <el-tab-pane label="下载列表" name="download">
            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <div class="downHeader">
                        <div class="filePath">下载列表</div>
                        <el-button class="download" type="text" @click="getDownloadList">刷新数据</el-button>
                    </div>
                </div>
                <el-table :data="downloadList" v-loading="downloadListLoading">
                    <el-table-column prop="icon_link" label="" width="52">
                        <template slot-scope="scope">
                            <el-image style="width: 32px; height: 32px" :src="scope.row.icon_link"></el-image>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="名称"></el-table-column>
                    <el-table-column label="下载进度">
                        <template slot-scope="scope">
                            <span> {{ sizeParse(parseInt(scope.row.file_size) * scope.row.progress / 100) || '0M' }} / {{sizeParse(parseInt(scope.row.file_size))}}</span>
                            <el-progress :text-inside="true" :stroke-width="20" :percentage="scope.row.progress || 0" text-color="#fff"></el-progress>
                        </template>
                    </el-table-column>
                    <el-table-column label="下载地址" show-overflow-tooltip>
                        <template slot-scope="scope">
                            {{scope.row.params.real_path}}
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </el-tab-pane>
    </el-tabs>

    <el-dialog title="下载路径" :visible.sync="showDownload" width="600px">
        <el-table :data="downloadPathList" highlight-current-row   v-loading="downloadPathLoading"
                  @current-change="handleCurrentChange">
            <el-table-column type="index" label="序号" width="50"></el-table-column>
            <el-table-column prop="RealPath" label="路径"></el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
             <el-button @click="downloadPath">刷新下载路径</el-button>
            <el-button @click="showDownload = false">取 消</el-button>
            <el-button type="primary" @click="downloadBatch">确 定</el-button>
        </span>
    </el-dialog>
</div>
</body>
<!-- import Vue before Element -->
<script src="/js/vue.js"></script>
<!-- import JavaScript -->
<script src="/js/element.js"></script>
<script>
    const request = (url, config, method = 'post') => {
        return fetch(url, {
            method,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(config)
        }).then(data => {
            return data.json()
        }).then(data => {
            if (data.code !== 200) {
                Vue.prototype.$message.error('请求出错:' + data.msg)
                return Promise.reject(data)
            }
            console.log(data)
            return data
        })
    }
    const api = {
        watch(config) {
            return request('/api/watch', config)
        },
        downloadPath(config) {
            return request('/api/downloadPath', config)
        },
        files(config) {
            return request('/api/files', config)
        },
        task(config) {
            return request('/api/task', config)
        },
        tasks(config) {
            return request('/api/tasks', config)
        }
    }

    new Vue({
        el: '#app',
        data() {
            return {
                activeName: 'files',
                baseInfoStr: localStorage.getItem("baseInfoStr") || null,
                baseInfo: {header: {}, params: {}},
                currentDownloadPath: {},
                downloadPathList: [],
                downloadPathLoading: false,
                fileList: [],
                fileListSelection: [],
                fileListLoading: false,
                downloadListLoading: false,
                downloadList: [],
                showDownload: false,
                filePaths: [],
                nextPageToken:null,
                currentParentId:null,
            }
        },
        created() {
            if (this.baseInfoStr) {
                this.parseBaseInfo();
            }
        },
        methods: {
            downloadBatch() {
                if (!this.currentDownloadPath.Id) {
                    this.$message.error('请选择路径')
                    return
                }
                for (let item of this.fileListSelection) {
                    this.download(item)
                }
            },
            download(file) {
                let data = this.cloneData(this.baseInfo)
                data.body = {
                    "type": "user#download",
                    "name": file.name,
                    "file_name": file.name,
                    "file_size": file.size + "",
                    "space": this.baseInfo.body.target,
                    "params": {
                        "target": this.baseInfo.body.target,
                        "file_id": file.id,
                        "total_file_count": "1",
                        "parent_folder_id": this.currentDownloadPath.Id,
                        "sub_file_index": "--1,",
                        "mime_type": ""
                    }
                }
                console.log(data)
                api.task(data).then(() => {
                    this.$message.success('创建任务成功')
                })
            },
            handleFileListSelectionChange(val) {
                this.fileListSelection = val
            },
            fileListSelectDisabled(data) {
                if (data.size) return true
                return false
            },
            sizeParse(size) {
                let k = 1024;
                if (!size) {
                    return ''
                } else if (size > Math.pow(k, 3)) {
                    return Math.ceil((size / Math.pow(k, 3)) * 10) / 10 + 'G'
                } else if (size > Math.pow(k, 2)) {
                    return Math.ceil((size / Math.pow(k, 2)) * 10) / 10 + 'M'
                } else {
                    return size + 'k'
                }
            },
            fileListClick(data) {
                if (data.size) {
                    return
                }
                this.filePaths.push(data)
                this.files(data.id)
            },
            handleCurrentChange(val) {
                this.currentDownloadPath = val
            },
            parseBaseInfo() {
                if (!this.baseInfoStr) {
                    this.$message.error("请输入内容")
                }
                localStorage.setItem("baseInfoStr", this.baseInfoStr)
                let temp = this.baseInfoStr.split('\n');
                for (let item of temp) {
                    let end = item.length - 1
                    // 去除 / 斜杠 和 空格
                    let end2 = end - 2
                    if (item.substring(0, 4) === 'curl') {
                        let url = item.substring(6, end2)
                        let mid = url.indexOf('index.cgi')
                        this.baseInfo.baseURL = url.substring(0, mid + 9)
                        this.baseInfo.url = url.substring(mid + 9)
                        this.baseInfo.queryStr = this.baseInfo.url.substring(this.baseInfo.url.indexOf('?') + 1)
                        let queryArr = this.baseInfo.queryStr.split('&')
                        for (let ele of queryArr) {
                            let t = ele.split('=')
                            this.baseInfo.params[t[0]] = t[1]
                        }
                    } else if (item.substring(2, 4) === '-H') {
                        let str = item.substring(6, end2).split(':')
                        if (str.length <= 1) {
                            str = [item.substring(6, end2).replace(';', ''), '']
                        }
                        this.baseInfo.header[str[0]] = str[1]?.substring(1) || ''

                    } else if (item.substring(2, 12) === '--data-raw') {
                        this.baseInfo.body = JSON.parse(item.substring(14, end2))
                    }
                }
                console.log(this.baseInfo)
                if (this.baseInfo.url) {
                    this.$message.success("解析成功")
                    this.downloadPath()
                    this.files()
                    this.getDownloadList()
                }
            },
            watch() {
                this.downloadListLoading = true;
                return api.watch(this.baseInfo)
            },
            downloadPath() {
                this.downloadPathLoading = true;
                return api.downloadPath(this.baseInfo).then(({data}) => {
                    this.downloadPathLoading = false;
                    this.downloadPathList = data
                })
            },
            files(parentId) {
                this.fileListLoading = true;
                this.currentParentId = parentId || this.currentParentId;
                let data = this.cloneData(this.baseInfo)
                data.params = {
                    ...this.baseInfo.params,
                    parent_id: this.currentParentId,
                    limit: 50,
                    page_token: this.nextPageToken,
                }
                return api.files(data).then(({data}) => {
                    this.fileList = data.files
                    this.nextPageToken = data.next_page_token
                    this.fileListLoading = false;
                })
            },
            filesRoute(parentId, index) {
                this.filePaths.splice(index)
                console.log(this.filePaths)
                this.files(parentId)
            },
            getDownloadList() {
                this.downloadListLoading = true;
                let data = this.cloneData(this.baseInfo)
                data.params['space'] = this.baseInfo.body.target
                data.params['limit'] = 100
                data.params['filters'] = '{"phase":{"in":"PHASE_TYPE_PENDING,PHASE_TYPE_RUNNING,PHASE_TYPE_PAUSED,PHASE_TYPE_ERROR"},"type":{"in":"user#download-url,user#download"}}'
                return api.tasks(data).then(({data}) => {
                    this.downloadListLoading = false;
                    this.downloadList = data.tasks
                })
            },
            cloneData(source) {
                return JSON.parse(JSON.stringify(source))
            }
        }
    })


</script>
</html>